package com.dream.jump.ui.welcome

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.dream.jump.databinding.ActivityWelcomeBinding
import com.dream.jump.ui.login.LoginActivity
import com.dream.jump.util.ConstantUtil
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class WelcomeActivity : AppCompatActivity() {
    private val welcomeViewModel: WelcomeViewModel by viewModels()
    private lateinit var binding: ActivityWelcomeBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWelcomeBinding.inflate(layoutInflater)
        welcomeViewModel.welcomeResult.observe(this@WelcomeActivity, Observer {
            if (it.result) {
                startActivity(Intent(this, LoginActivity::class.java))
            }
        })
        requestPermissions(
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ), ConstantUtil.REQUEST_CODE_PERMISSIONS
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == ConstantUtil.REQUEST_CODE_PERMISSIONS) {
            if (grantResults.find { result -> result != PackageManager.PERMISSION_GRANTED } !== null) {
                Toast.makeText(this, "申请权限失败，无法初始化。", Toast.LENGTH_SHORT).show()
                finish()
            } else {
                welcomeViewModel.initData()
            }
        }
    }

}